package jh.com.jhappbf.weight.query;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbDialogFragment.AbDialogOnLoadListener;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.ab.view.pullview.AbPullToRefreshView.OnFooterLoadListener;
import com.ab.view.pullview.AbPullToRefreshView.OnHeaderRefreshListener;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;

import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.PlanModel;
import jh.com.jhappbf.utils.JsonHelper;


public class SelectActivity extends AbActivity {
    private RelativeLayout mContentView;
    private RelativeLayout mErrorView;
    private SearchView mSearchView;
    private AbPullToRefreshView mRefreshView;
    private ListView mListView;
    private List<String> mData;
    private ArrayAdapter<String> mAdapter;
    private Button mBtnTryAgin;
    private AbLoadDialogFragment mDialogFragment = null;
    private Context mAppContext;
    private String mFlag = "";
    private String mFileName ="";
    private AbTitleBar mAbTitleBar;
    private String mValue= "" ;
    private List<JSONObject> newListData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.query_weight_setting_select_llistview);
        mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackground(R.drawable.top_bg);
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.drawable.line);
        initView();
    }

    private void initView() {
        Intent intent =  getIntent();
        if(intent != null)
        {
            mFlag = intent.getStringExtra("flag");
        }

        if(mFlag.equals("cargoname"))
        {
            mAbTitleBar.setTitleText(R.string.query_weight_setting_select_cargoname);
        }
        if(mFlag.equals("unloadUnit"))
        {
            mAbTitleBar.setTitleText("组织单位");
            mValue = "备用9";
        }
        if(mFlag.equals("unloadArea"))
        {
            mAbTitleBar.setTitleText("库位");
            mValue = "备用7";
        }
        else if(mFlag.equals("platenumber"))
        {
            mAbTitleBar.setTitleText(R.string.query_weight_setting_select_platenumber);
        }
        else if(mFlag.equals("dispatchId"))
        {
            mAbTitleBar.setTitleText("派车申请单");
            mValue = "dispatchId";
        }
        else if(mFlag.equals("type"))
        {
            mAbTitleBar.setTitleText(R.string.query_weight_setting_select_type);
            mValue = "l";
        }
        else if(mFlag.equals("sender"))
        {
            mAbTitleBar.setTitleText(R.string.query_weight_setting_select_sender);
            mValue = "f";
        }
        else if(mFlag.equals("receiver") || mFlag.equals("contractUnit"))
        {
            mAbTitleBar.setTitleText(R.string.query_weight_setting_select_receiver);
            mValue = "s";
        }
        else if(mFlag.equals("cargoname1"))
        {
            mAbTitleBar.setTitleText(R.string.query_weight_setting_select_cargoname);
            mValue="h";
        }
        else if(mFlag.equals("S3"))
        {
            mAbTitleBar.setTitleText(R.string.query_weight_setting_select_sitepoint);
            mValue="备用3";
        }
        else if(mFlag.equals("contract"))
        {
            mAbTitleBar.setTitleText(R.string.query_weight_setting_select_contract);
            mValue="contract";
        }

        mContentView = (RelativeLayout) findViewById(R.id.query_setting_search_content);
        mErrorView = (RelativeLayout) findViewById(R.id.query_setting_error_view);
        mSearchView = (SearchView) findViewById(R.id.query_setting_search_view);
        mRefreshView = (AbPullToRefreshView) findViewById(R.id.query_setting_select_pullToRefreshView);
        mListView = (ListView) findViewById(R.id.query_setting_select_listView);
        mBtnTryAgin = (Button) findViewById(R.id.query_setting_error_btn);
        mAppContext = getApplicationContext();

        // 重试
        mBtnTryAgin.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                LoadFirst();
            }
        });

        // 下拉刷新
        mRefreshView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {

            @Override
            public void onHeaderRefresh(AbPullToRefreshView view) {
                refreshTask();
            }
        });

        // 上拉加载更多
        mRefreshView.setOnFooterLoadListener(new OnFooterLoadListener() {

            @Override
            public void onFooterLoad(AbPullToRefreshView view) {
                refreshTask();
            }
        });

        // 单击数据项
        mListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                TextView txt = (TextView)view;
                Intent i = new Intent();
                if(mFlag.equals("contract"))
                {
                    JSONObject obj = newListData.get(position);
                    PlanModel model = new PlanModel();
                    model.setSender(obj.optString("发货"));
                    model.setReceiver(obj.optString("收货"));
                    model.setType(obj.optString("类型"));
                    i.putExtra("result", model);
                }else if (mFlag.equals("dispatchId")){
                    JSONObject obj = newListData.get(position);
                    if (TextUtils.equals("0",obj.optString("states"))){
                        AbToastUtil.showToast(SelectActivity.this,"未审核申请单不可选");
                        return;
                    }
                    i.putExtra("result", obj.optString("CardID"));
                }
                else
                {
                    i.putExtra("result", txt.getText());
                }

                setResult(0, i);
                SelectActivity.this.finish();
            }
        });

        mListView.setTextFilterEnabled(true);
        mSearchView.setOnQueryTextListener(new OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if(TextUtils.isEmpty(newText))
                {
                    mListView.clearTextFilter();
                }
                else
                {
                    mListView.setFilterText(newText);
                }
                return true;
            }
        });
        // 设置进度条的样式
        mRefreshView.getHeaderView().setHeaderProgressBarDrawable(
                this.getResources().getDrawable(R.drawable.progress_circular));
        mRefreshView.getFooterView().setFooterProgressBarDrawable(
                this.getResources().getDrawable(R.drawable.progress_circular));

        mData =new ArrayList<String>();
        LoadFirst();
        mAdapter = new ArrayAdapter<String>(mAppContext, R.layout.list_view_item_txt, R.id.list_view_item_txt, mData);
        mListView.setAdapter(mAdapter);

    }

    /**
     * 第一次加载
     */
    private void LoadFirst() {
        mDialogFragment = AbDialogUtil.showLoadDialog(SelectActivity.this,
                R.drawable.ic_load, "查询中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(new AbDialogOnLoadListener() {

            @Override
            public void onLoad() {
                mErrorView.setVisibility(View.GONE);
                mContentView.setVisibility(View.VISIBLE);
                refreshTask();
            }
        });
    }

    /**
     * 下拉刷新
     */
    private void refreshTask() {
        ArrayList<String> param = new ArrayList<String>();
        final ArrayList<String> value = new ArrayList<String>();
        String methodName = "getCargoname";
        mFileName= "Cargoname";
        if(mFlag.equals("cargoname"))
        {
            methodName = "getCargoname";
            mFileName ="Cargoname";
        }
        else if(mFlag.equals("platenumber"))
        {
            methodName = "getPlatenumber";
            mFileName = "Platenumber";
        }
        else if(mFlag.equals("platenumberSelect"))
        {
            methodName = "getBusinessPlatenumber";
            mFileName = "Platenumber";
        }
        else if(mFlag.equals("contract"))
        {
            methodName = "getContract";
            mFileName  = "收货";
        }
        else if(mFlag.equals("S3"))
        {
            methodName="getSaverFiledVal";
            param.add("filed");
            value.add(mFlag);
            mFileName=mFlag;
        }
        else
        {
            param.add("filedName");
            value.add(mValue);
            methodName = "getFiledValue";
            mFileName = "cczz";
        }


        Listener<String> listener = new Listener<String>() {
            @Override
            public void onResponse(String response) {

                AbDialogUtil.removeDialog(SelectActivity.this);
                mDialogFragment.dismiss();
                mRefreshView.onHeaderRefreshFinish();
                mRefreshView.onFooterLoadFinish();
                mErrorView.setVisibility(View.GONE);
                mContentView.setVisibility(View.VISIBLE);

                newListData = JsonHelper
                        .getJsonObjects(response);
                if (newListData != null) {
                    mData.clear();
                    String[] arr = mFileName.split(",");

                    String valTmp ;
                    for (int i = 0; i < newListData.size(); i++) {
                        JSONObject obj = newListData.get(i);
                        StringBuilder contentVal= new StringBuilder();
                        if(obj != null)
                        {
                            int index=0;
                            for (String item : arr) {
                                if(index > 0)contentVal.append("; ");
                                if (item.equals("states")){
                                    if (obj.optString(item).equals("0")){
                                        contentVal.append("未审核");
                                    }else if (obj.optString(item).equals("01")){
                                        contentVal.append("已审核");
                                    }
                                }else {
                                    contentVal.append(obj.optString(item)) ;
                                }
                                index++;
                            }

                            valTmp = contentVal.toString();
                            if(!TextUtils.isEmpty(valTmp))
                            {
                                mData.add(valTmp);
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                }
            }
        };

        ErrorListener errorListener = new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                AbDialogUtil.removeDialog(SelectActivity.this);
                mDialogFragment.dismiss();
                mRefreshView.onHeaderRefreshFinish();
                mRefreshView.onFooterLoadFinish();
                mErrorView.setVisibility(View.VISIBLE);
                mContentView.setVisibility(View.GONE);
                mData.clear();
                mAdapter.notifyDataSetChanged();
            }
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }
}
